package P8;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @Author Luming
 * @Date 2024/6/11 14:31
 * @Description:
 */
public class DateTimeUDPServer {
    private final static int PORT = 13;
    
    public static void main(String[] args) {
        try (DatagramSocket socket = new DatagramSocket(PORT)) {
            while (true) {
                try {
                    DatagramPacket request = new DatagramPacket(new byte[1024], 1024);
                    socket.receive(request);
                    
                    String daytime = new Date().toString();
                    byte[] data = daytime.getBytes(StandardCharsets.US_ASCII);
                    DatagramPacket response = new DatagramPacket(data, data.length, request.getAddress(), request.getPort());
                    socket.send(response);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}



//package P8;
//
//import java.io.IOException;
//import java.net.DatagramPacket;
//import java.net.DatagramSocket;
//import java.util.Date;
//import java.util.logging.Logger;
//
///**
// * @Author Luming
// * @Date 2024/6/11 14:31
// * @Description:
// */
//public class DateTimeUDPServer {
//    private final static int PORT = 13;
//    private final static Logger audit = Logger.getLogger("requset");
//    private final static Logger errors = Logger.getLogger("errors");
//
//    public static void main(String[] args) {
//        try (DatagramSocket socket = new DatagramSocket(PORT)) {
//            try {
//                while (true) {
//                    DatagramPacket request = new DatagramPacket(new byte[1024], 1024);
//                    socket.receive(request);
//                    String daytime = new Date().toString();
//                    byte[] data = daytime.getBytes("US-ASCII");
//                    DatagramPacket response = new DatagramPacket(data, data.length, request.getAddress(), request.getPort());
//                    socket.send(response);
//                    audit.info(daytime + " " + request.getAddress());
//                }
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//    }
//}
